﻿$(function () {

    $(".dropdown-tree").each(function(i, e) {
        var name = $(e).data("name");
        var url = $(e).data("url");
        var cascade = $(e).data("cascade");
        var milti = $(e).data("milti");
        var callbackevent = $(e).data("callbackevent");
        var valueInput = $("#" + name);
        var nameInput = $("#text_" + name);

        $("#dropDownTree_" + name).click(function(e) {
            e.stopPropagation();
        });


        var dropDownSetting = {
            callback: {
                onCheck: function (event, treeId, treeNode) {

                }
            },
            view: {
                showLine: true,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };

        if (milti === "True") {
            dropDownSetting.view.selectedMulti = true;
            dropDownSetting.check.enable = true;
            dropDownSetting.check.chkboxType = cascade === "True" ? { 'Y': 'ps', 'N': 'ps' } : { 'Y': '', 'N': '' };
        } else {
            dropDownSetting.callback.onClick = function(event, treeId, treeNode) {
                if (treeNode.chkDisabled)
                    return;

                $('#' + name).val(treeNode.id);
                $('#text_'+name).val(treeNode.name);
                $("#btn_" + name).click();

                if (callbackevent !== "" && callbackevent != null) {

                    eval(callbackevent)(treeId, treeNode);
                }
            }
        }

        $.ajax({
            type: 'post',
            url: url,
            dataType: 'json',
            contentType: 'application/json',
            beforeSend: function () {
                abp.ui.setBusy('#zDropDownTree_'+name);
            },
            success: function (data) {
                abp.ui.clearBusy('#zDropDownTree_' + name);

                if (data.result)
                    data = data.result;

                var tree = $.fn.zTree.init($('#zDropDownTree_' + name), dropDownSetting, data);
                var value = valueInput.val();
                var values = value.split(',');
                var namnes = [];

                $(values).each(function (i, e) {
                    var defualtNode = tree.getNodeByParam('id', e, null);
                    if (defualtNode)
                        namnes.push(defualtNode.name);
                });

                nameInput.val(namnes.splice(','));
            },
            error: function (xhr) {
                abp.ui.clearBusy($('#zDropDownTree_' + name));
            }
        });
    });
});

function _checkClass(e, className) {
    var result = e.hasClass(className);
    var parent = e.parent();

    while (parent.length > 0 && !result) {
        result = parent.hasClass(className);
        parent = parent.parent();
    }

    return result;
}